Basic C Programming (Part 3)

By Arthur Ed LeBouthillier

This article appeared in the February 2000 issue of The Robot Builder.

This article is a foolow-up to "Basic C Programming (Part 2)"

The printf Function

Last month we introduced the printf function. printf is known as a formatted output function because it allows one to present data in specific formats. The general syntax of a printf function is:

printf( control_string, arg1, …, argn );

The first argument that the printf command takes is a control string. A string is a sequence of printable characters in between double quotes (“). The printf also can take any number of arguments after the control string.

The printf Control String

The control string allows you to place a sequence of printable characters, control sequence characters and conversion characters together for sending to the computer’s display. Let’s suppose you wanted the words ‘hello world’ to appear on your computer screen. To do this, your printf statement would look like this:

printf(“hello world”);

Were you to include this line in a program, and run it, the words ‘hello world’ would appear on the screen. Let’s assume you wanted to use two printfstatements one after the other to print different strings on different lines:

printf(“Hello Dave,”);
printf(“I’m sorry I can’t do that.”);

The resulting output would look like this:

Hello Dave,I’m sorry I can’t do that.

This is not quite what we intended because the outputs of the two printf statements appeared immediately one after the other. We would need to have some sort of way of telling the printf statement to put the output from the second printf on another
line. C provides this capability by using character sequences to signify special operations.

Escape Characters

In order to allow the sending of non-printable characters to the display using the printf function, C uses the ‘\’ (backslash) character to signify an escape sequence. There are a few predefined escape sequences:

\n line feed
\r carriage return
\t tab
\0 null
\\ backslash
\’ singe quote

In general, C allows you to send any ascii character using an escape sequence by writing:

\ddd

where ddd are three octal digits (digits from 0 to 7). Therefore, you could also send a formfeed by sending the escape sequence, ‘\014’, which is an octal 14 (or decimal 12). You can include these escape sequences inside of the control string of the printf function in order to control how your control string is printed. The proper way to print those two strings on separate lines would be to include a ‘\n’ escape sequence in the control string:

printf(“Hello Dave,\n”);
printf(“I’m sorry I can’t do that.\n”);

The printf function has very sophisticated display capabilities which we’ll look at more next month.

As a refresher, here’s the ‘hello world’ program from last month. The printf statement should make more sense now:

#include <stdio.h>
void main()
{
printf(“Hello world.\n”);
}